package com.heima.article.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.minio.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.pojos.ArticleVisitStreamMess;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        List<ApArticle> apArticleList = apArticleMapper.load(dto, (short)1);
        return ResponseResult.okResult(apArticleList);
    }

    @Override
    public ResponseResult load2(ArticleHomeDto dto) {
        if(dto == null){
            log.warn("入参不能为空");
            return ResponseResult.okResult("");
        }
        String tag = dto.getTag();//频道id
        //搜索缓存数据
        String hotArticleCache = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + tag);
        if(StringUtils.isEmpty(hotArticleCache)){
            //走原来流程
            return load(dto);
        }
        List<ApArticle> apArticles = JSON.parseArray(hotArticleCache, ApArticle.class);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadMore(ArticleHomeDto dto, Short loadType) {
        List<ApArticle> apArticleList = apArticleMapper.load(dto, loadType);
        return ResponseResult.okResult(apArticleList);
    }

    @Override
    public ResponseResult loadNew(ArticleHomeDto dto, Short loadType) {
        List<ApArticle> apArticleList = apArticleMapper.load(dto, loadType);
        return ResponseResult.okResult(apArticleList);
    }

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private FreemarkerGenerator freemarkerGenerator;
    @Autowired
    private MinIoTemplate minIoTemplate;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Override
    @Async
    public void generate(Long articleId) {
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId,articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
        if(apArticleContent == null){
            log.warn("文章内容不存在");
            return;
        }
        HashMap<String, Object> map = new HashMap<>(1);
        String content = apArticleContent.getContent();
        map.put("content", JSON.parseArray(content));

        InputStream inputStream = freemarkerGenerator.generate("article.ftl", map);
        String url = minIoTemplate.uploadFile("", articleId + ".html", inputStream, "html");

        //查询ApArticle,修改里面对应信息的Static_Url字段
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if(apArticle == null){
            log.warn("文章为空");
            return;
        }
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String content = dto.getContent();
        Long id = dto.getId();

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        if(id == null){
            int insertResult = apArticleMapper.insert(apArticle);
            if(insertResult < 1){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章新增失败");
            }

            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDelete(false);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsForward(true);
            apArticleConfig.setArticleId(apArticle.getId());
            int insertConfigResult = apArticleConfigMapper.insert(apArticleConfig);
            if(insertConfigResult < 1){
                log.warn("文章配置表插入失败");
                throw new RuntimeException("文章配置表插入失败");
            }

            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(content);
            apArticleContent.setArticleId(apArticle.getId());
            int insertContentResult = apArticleContentMapper.insert(apArticleContent);
            if(insertContentResult < 1){
                log.warn("文章内容表插入失败");
                throw new RuntimeException("文章内容表插入失败");
            }
            generate(apArticle.getId());

            return ResponseResult.okResult(apArticle.getId());
        }else {
            int updateResult = apArticleMapper.updateById(apArticle);
            if(updateResult < 1){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章修改失败");
            }
            ApArticleContent contentUpdate = new ApArticleContent();
            contentUpdate.setContent(content);
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId,id);
            int contentUpdateResult = apArticleContentMapper.update(contentUpdate, wrapper);
            if(contentUpdateResult < 1){
                log.warn("文章内容表修改失败");
                throw new RuntimeException("文章内容表修改失败");
            }

            generate(id);
            return ResponseResult.okResult(id);
        }
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public void sendIndexUpdate(ApArticle article, String content) {
        if(article == null || StringUtils.isBlank(content)){
            log.warn("入参不能为空");
            return;
        }

        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(article,searchArticleVo);
        searchArticleVo.setContent(content);
        kafkaTemplate.send("es.index.update",JSON.toJSONString(searchArticleVo));
    }


    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {

        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        boolean isfollow = false;
        boolean islike = false;
        boolean isunlike = false;
        boolean iscollection = false;

        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //喜欢行为
        String likeBehaviorJson= (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        if(StringUtils.isNotBlank(likeBehaviorJson)){
            islike = true;
        }
        //不喜欢的行为
        String unLikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        if(StringUtils.isNotBlank(unLikeBehaviorJson)){
            isunlike = true;
        }

        //是否收藏
        String collctionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR+dto.getArticleId(), user.getId().toString());
        if(StringUtils.isNotBlank(collctionJson)){
            iscollection = true;
        }

        //是否关注
        Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getAuthorId().toString());
        System.out.println(score);
        if(score != null){
            isfollow = true;
        }
        Map<String, Object> resultMap = new HashMap<>(4);
        resultMap.put("isfollow", isfollow);
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);

        return ResponseResult.okResult(resultMap);
    }

    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        // 更新数据库
        ApArticle article = updateArticle(mess);
        if (article == null) {
            return;
        }

        // 计算文章分值
        Integer score = compute(article);

        // 替换当前文章对应频道的热点数据
        replaceToRedis(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + article.getChannelId());

        // 替换推荐频道热点数据
        replaceToRedis(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 替换缓存数据
     *
     * @param article 文章内容
     * @param score   分值
     * @param key     缓存键
     */
    private void replaceToRedis(ApArticle article, Integer score, String key) {
        // 根据key获取缓存数据
        String cache = cacheService.get(key);
        if (StringUtils.isEmpty(cache)) {
            return;
        }

        List<HotArticleVo> hotArticleVos = JSON.parseArray(cache, HotArticleVo.class);
        if (CollectionUtils.isEmpty(hotArticleVos)) {
            return;
        }

        boolean flag = false;

        // 如果当前内容存在于缓存，则替换缓存分值
        for (HotArticleVo hotArticleVo : hotArticleVos) {
            if (hotArticleVo == null) {
                continue;
            }

            if (hotArticleVo.getId().equals(article.getId())) {
                hotArticleVo.setScore(score);
                flag = true;
                break;
            }
        }

        //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
        if (flag) {
            if (hotArticleVos.size() >= 30) {
                // 排序
                hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                // 取最后一条
                HotArticleVo lastHot = hotArticleVos.get(hotArticleVos.size() - 1);
                // 如果最后一条分值比当前文章分值小，则替换
                if (lastHot.getScore() < score) {
                    hotArticleVos.remove(lastHot);
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(article, hot);
                    hot.setScore(score);
                    hotArticleVos.add(hot);
                }
            } else {
                HotArticleVo hot = new HotArticleVo();
                BeanUtils.copyProperties(article, hot);
                hot.setScore(score);
                hotArticleVos.add(hot);
            }
        }

        // 重新排序
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());

        // 缓存到redis
        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 更新文章MySQL数据
     *
     * @param mess messmess
     * @return ApArticle
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle == null) {
            log.warn("文章id" + mess.getArticleId() + "不存在");
            return null;
        }

        Integer views = apArticle.getViews();
        Integer likes = apArticle.getLikes();
        Integer comment = apArticle.getComment();
        Integer collection = apArticle.getCollection();

        apArticle.setComment(comment == null ? mess.getComment() : comment + mess.getComment());
        apArticle.setLikes(likes == null ? mess.getLike() : likes + mess.getLike());
        apArticle.setCollection(collection == null ? mess.getCollect() : collection + mess.getCollect());
        apArticle.setViews(views == null ? mess.getView() : views + mess.getView());

        apArticleMapper.updateById(apArticle);

        return apArticle;
    }

    /**
     * 计算文章评分
     *
     * @param apArticle apArticle
     * @return Integer
     */
    private Integer compute(ApArticle apArticle) {
        Integer views = apArticle.getViews();
        Integer likes = apArticle.getLikes();
        Integer comment = apArticle.getComment();
        Integer collection = apArticle.getCollection();

        Integer score = 0;
        if (views != null) {
            score += views;
        }

        if (likes != null) {
            score += likes * 3;
        }

        if (comment != null) {
            score += comment * 5;
        }

        if (collection != null) {
            score += collection * 8;
        }

        return score;
    }
}
